package com.atguigu.flink.timeAndwindow;

import com.atguigu.flink.func.ClickSource;
import com.atguigu.flink.pojo.Event;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;

/**
 * Created by 黄凯 on 2023/6/17 0017 13:29
 *
 * @author 黄凯
 * 永远相信美好的事情总会发生.
 */
public class Flink05_SimpleAggFunction {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<Event> ds = env.addSource(new ClickSource())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                                .withTimestampAssigner(
                                        (event, ts) -> event.getTs()
                                )
                );
        ds.print("input");

        //需求: 统计每10秒内每个用户的点击次数
        ds.map(
                event -> Tuple2.of(event.getUser(), 1)
        ).returns(
                Types.TUPLE(Types.STRING, Types.INT)
        ).keyBy(
                t -> t.f0
        ).window(
                TumblingEventTimeWindows.of(Time.seconds(10))
        ).sum(
                1
        ).print();

        env.execute();

    }

}
